﻿#include "UnstructuredMesh.h"
#include "MeshTool.h"

RegisterObject(UnstructuredMesh);

UnstructuredMesh::UnstructuredMesh(const Configuration& cfg)
  : Mesh(cfg)
  , _triangularization(Get<bool>("triangularization", false))
{
  _dims = GetVectorValue<int>("dims");

  if (_dims.size() == 1)
  {
    Error("一维网格生成不支持");
  }
  else if (_dims.size() == 2)
  {
    _x_ranges = GetVectorValue<Real>("x_range");
    _y_ranges = GetVectorValue<Real>("y_range");
  }
  else if (_dims.size() == 3)
  {
    _x_ranges = GetVectorValue<Real>("x_range");
    _y_ranges = GetVectorValue<Real>("y_range");
    _z_ranges = GetVectorValue<Real>("z_range");
  }
  else
  {
    Error("dim设置错误");
  }
}

void UnstructuredMesh::Build()
{
  if (_prepared) //已经创建过
    return;


  if (_dims.size() == 2)
  {
    Vec2f start{ _x_ranges[0], _y_ranges[0] };
    Vec2f end{ _x_ranges[1], _y_ranges[1] };
    Vec2f space = end - start;
    Id2 point_dim = { _dims[0] + 1, _dims[1] + 1 };

    for (size_t i = 0; i < 2; i++)
      space[i] = (end[i] - start[i]) / _dims[i];


    _data_set = MeshTool::CreateStructuredMesh(point_dim, start, space);
  }

  else if (_dims.size() == 3)
  {
    Vec3f start{ _x_ranges[0], _y_ranges[0], _z_ranges[0] };
    Vec3f end{ _x_ranges[1], _y_ranges[1], _z_ranges[1] };
    Vec3f space = end - start;
    Id3 point_dim = { _dims[0] + 1, _dims[1] + 1, _dims[2] + 1 };

    for (size_t i = 0; i < 3; i++)
      space[i] = (end[i] - start[i]) / _dims[i];


    _data_set = MeshTool::CreateStructuredMesh(point_dim, start, space);
  }

  else
  {
    Error("dim设置错误");
  }

  if (_triangularization)
  {
    MeshTool::TriangulateMesh(*this);
    //vtkm::filter::Triangulate triangulateFilter;
    //vtkm::cont::DataSet output = triangulateFilter.Execute(data_set);
    //this->_cell_set = output.GetCellSet();
    //ArrayHandle<Vec3f> pts;
    //Invoker{}(CoodConvert{}, output.GetCoordinateSystem(), pts);
    //this->_coord = CoordinateSystem("coord", pts);
  }

  //BuildFaceTopo();
  Prepared();
}
